package patternmining.model.construction;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**Implements an index for the members of all the registered packages.
 * Permits to obtain a list of the qualified names of all the types defiened in a package, provided
 * that the types have been registered before.
 * 
 * Usage:
 * instance.addType("java.lang", "String"); instance.add("java.lang", "Integer"); instance.add("customPackage", "ClassX");
 * String[] members = instance.getMembersOfPackage("java.lang"); // members would be { "String", "Integer" }
 * 
 * @version 1.0, 04.07.2008
 * @author Holger Wiehen
 */
class PackageIndex {

    private Map<String , Set<String> > packageToMemberMapping;
    
    public PackageIndex(){
        packageToMemberMapping = new HashMap<String, Set<String> >();
    }
    
    /**Adds the supplied type to the index of members of the supplied package
     * 
     * @param packageName
     * @param typeName the SIMPLE name of the type ex. String, ClassX
     */
    public void addType( String packageName, String typeName){
        String qualifiedName = packageName + "." + typeName;
        //verify if the packageName is already included.
        if( packageToMemberMapping.containsKey( packageName ) ){
            //obtain the list of tyesnames referenced by this package name, add the new type
            Set<String> includedTypes = packageToMemberMapping.get(packageName);
            includedTypes.add(qualifiedName);
            //the new type name is now included in the list referenced by this package name
        }
        else{
            //create a new list of typesnames and add it to the mapping together with the paclkage name as the key
            Set<String> includedTypes = new HashSet<String>();
            includedTypes.add(qualifiedName);
            packageToMemberMapping.put(packageName, includedTypes);
        }           
    }
    
    /**Returns the fully qualified names of the members of the package
     * 
     * @param packageName
     * @return
     */
    public String[] getMembersOfPackage(String packageName){
        Set<String> includedTypes = packageToMemberMapping.get(packageName);
        if( includedTypes == null ) return null;
        String[] members = includedTypes.toArray( new String[ includedTypes.size() ] );
        return members;
    }
    
}
